#include "db.h"
#include "user.h"
#include "time.h"

#include <iostream>
#include <signal.h>

#include <boost/program_options.hpp>
#include <boost/asio.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>


#include "mainserver.h"

boost::function0<void> ctrlc;
void sighandler(int i)
{
//  signal(SIGINT, sighandler);
  std::cout << "calling server stop" << std::endl;
  ctrlc();
}

namespace po = boost::program_options;


int main(int argc, char * argv[])
{

  // ********************
  // program options
  // ********************

  int output_level;
  int port;
  int data_port;


  po::options_description desc("Options");

  desc.add_options()
    ("help", "produce help message")
    ("output,o", po::value<int>(&output_level)->default_value(6), "set output level")
    ("master port,P", po::value<int>(&port)->default_value(9790), "set server master port")
    ("data port,p", po::value<int>(&data_port)->default_value(9791), "set server data port")
    ;

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);


  // handling options:

  if (vm.count("help"))
  {
    std::cout << desc << std::endl;
    return 1;
  }
 

  std::clog << "Program Options" << std::endl;

  std::clog << "[OPT] output = " << output_level << std::endl;

  std::clog << "[OPT] master port = " << port << std::endl;

  std::clog << "[OPT] data port = " << data_port << std::endl;

  std::clog << std::endl;




  // ******************
  // server loop
  // ******************

  mainServer * server = 0;
  try
  {
    server = new mainServer("localhost", port);


    ctrlc = boost::bind(&mainServer::stop, server);

    signal(SIGINT, sighandler);

    server->run();
  }
  catch (std::exception &e)
  {
    std::cerr << e.what() << std::endl;
  }

  if (server != 0)
  {
    delete server;
  }

  return 0;
}


